/* eslint-disable no-mixed-spaces-and-tabs */
/*
 * @Author: lp
 * @Date: 2022-02-08 11:36:57
 * @LastEditTime: 2022-04-08 17:52:13
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: //nien-vue3-admin//src//utils//scrollTo.ts
 */
declare const window: Window & {
  webkitRequestAnimationFrame: () => () => void,
  document: {
    body: {
      parentNode: {
        scrollTo: () => void;
        scrollTop: number;
      }
    }
  }
}
Math.easeInOutQuad = function (t, b, c, d) {
  t /= d / 2
  if (t < 1) return (c / 2) * t * t + b
  t--
  return (-c / 2) * (t * (t - 2) - 1) + b
}
const requestAnimFrame = function () {
  return (
    window.requestAnimFrame
    || window.webkitRequestAnimationFrame
    || window.mozRequestAnimationFrame
    || function (callback) {
      setTimeout(callback, 1000 / 60)
    }
  )
}

function move(amount) {
  document.documentElement.scrollTo = amount
  window.document.body.parentNode.scrollTo = amount
  document.body.scrollTo = amount
}

function position() {
  return document.documentElement.scrollTop || window.document.body.parentNode.scrollTop || document.body.scrollTop
}

export function scrollTo(to: number, duration: number, callback?: () => void) {
  const start = position()
  const change = to - start
  const increment = 20
  let currentTime = 0
  duration = typeof duration === 'undefined' ? 500 : duration
  const animateScroll = function () {
    currentTime += increment
    // 时间动画曲线
    const val = Math.easeInOutQuad(currentTime, start, change, duration)
    move(val)
    if (currentTime <= duration) {
      requestAnimFrame()(animateScroll)
    } else {
      callback && callback()
    }
  }
  animateScroll()
}
